package top.cardone.validator.func;

import com.google.common.collect.Maps;
import lombok.Setter;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import top.cardone.core.util.func.Func4;

import java.util.Map;
import java.util.Objects;

/**
 * @author yao hai tao
 * @date 2016/9/19
 */
@Log4j2
public class RequiredValidatorFunc implements Func4<Map<String, Object>, Map<String, Object>, String, Object, Object> {
    @Setter
    protected String code = "required";

    @Override
    public Map<String, Object> func(Map<String, Object> map, String key, Object rule, Object message) {
        if (log.isDebugEnabled()) {
            log.debug(this.code + ":" + key);
        }

        if (rule instanceof Boolean) {
            if (BooleanUtils.isFalse((Boolean) rule)) {
                return null;
            }
        }

        Object val = MapUtils.getObject(map, key);

        if (!Objects.isNull(val)) {
            if (!(val instanceof String)) {
                return null;
            } else {
                String valString = (String) val;

                if (StringUtils.isNotBlank(valString)) {
                    return null;
                }
            }
        }

        return this.getMessage(key, message, new Object[0]);
    }

    protected Map<String, Object> getMessage(String key, Object message, Object[] args) {
        Map<String, Object> errorMap = Maps.newHashMap();

        Map<String, Object> valueMap = Maps.newHashMap();

        if (message instanceof Map) {
            Map<String, String> messageMap = (Map<String, String>) message;

            valueMap.put("code", StringUtils.defaultIfBlank(MapUtils.getString(messageMap, "code"), key));

            valueMap.put("defaultMessage", MapUtils.getString(messageMap, "defaultMessage"));
        } else {
            valueMap.put("code", key + StringUtils.SPACE + this.code);

            valueMap.put("defaultMessage", message);
        }

        valueMap.put("args", args);

        errorMap.put(MapUtils.getString(valueMap, "code", key), valueMap);

        return errorMap;
    }
}